#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- Excel Handler
# --
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2021/1/14 11:45
# Email lmay@lmaye.com
# ----------------------------------------------------------

from core import LOG
from utils import excel_utils
from utils.mongo_utils import Mongo


def export_data(excel_file, db="oms", tb=None, order_ids=None, column=None):
    """
    导出数据

    :param excel_file:  excel文件
    :param db:          数据库
    :param tb:          表
    :param order_ids:   订单ID
    :param column:      导出字段
    :return:
    """
    # MongoDB获取数据
    params = {}
    if order_ids is not None and (isinstance(order_ids, list) and len(order_ids) > 0):
        params = {"AmazonOrderId": {"$in": order_ids}}
    mongo = Mongo()
    documents = mongo.query(db, tb, params, column)
    # 数据处理
    records = []
    for document in documents:
        record = {}
        for key in document:
            if "_id" == key:
                continue
            value = document[key]
            if column is not None:
                if "ShippingAddress" == key:
                    if isinstance(value, str):
                        value = {
                            "StateOrRegion": "",
                            "PostalCode": "",
                            "City": "",
                            "CountryCode": ""
                        }
                    for key2 in value:
                        if "isAddressSharingConfidential" == key2:
                            continue
                        record[key2] = value[key2]
                else:
                    record[key] = value
            else:
                record[key] = value
        records.append(record)
    # 写入excel文件
    excel_utils.write_excel(excel_file, "Sheet1", records)
    # excel_utils.write_excel_append(excel_file, "Sheet2", records)


def export_data2(excel_file, order_ids=None):
    """
    导出数据

    :param excel_file: excel文件
    :param order_ids:
    :return:
    """
    # MongoDB获取数据
    params = {}
    if order_ids is not None and (isinstance(order_ids, list) and len(order_ids) > 0):
        params = {"orderNumber": {"$in": order_ids}}
    column = {"orderNumber": True, "orderDatetime": True, "PackageModelList": True}
    mongo = Mongo()
    documents = mongo.query("oms", "RakutenJPOrderItem2020all", params, column)
    # 数据处理
    records = []
    for document in documents:
        record = {}
        for key in document:
            if "_id" == key:
                continue
            value = document[key]
            if "PackageModelList" == key:
                for it in value:
                    x = 1
                    for it2 in it["ShippingModelList"]:
                        record["shippingDate" + str(x)] = it2["shippingDate"]
                        x += 1
            else:
                record[key] = value
        records.append(record)
    # 写入excel文件
    excel_utils.write_excel(excel_file, "Sheet1", records)


def export_data3(excel_file, db="oms", tb=None, order_ids=None, column=None):
    """
    导出数据

    :param excel_file:  excel文件
    :param db:          数据库
    :param tb:          表
    :param order_ids:   订单ID
    :param column:      导出字段
    :return:
    """
    # MongoDB获取数据
    params = {}
    if order_ids is not None and (isinstance(order_ids, list) and len(order_ids) > 0):
        params = {"AmazonOrderId": {"$in": order_ids}}
    mongo = Mongo()
    # documents = mongo.query(db, tb, params, column)
    documents = mongo.query_page(db, tb, params, column, page_size=20000, page_idx=2)
    # 数据处理
    row = 0
    records = []
    for document in documents:
        record = {}
        for key in column:
            try:
                value = document[key]
            except KeyError:
                record[key] = ""
                continue
            if "PromotionDiscountTax" == key:
                if isinstance(value, str):
                    value = {"PromotionDiscountTax Amount": ""}
                for key2 in value:
                    if "CurrencyCode" == key2:
                        continue
                    record["PromotionDiscountTax Amount"] = value[key2]
            elif "ItemTax" == key:
                if isinstance(value, str):
                    value = {"ItemTax Amount": ""}
                for key2 in value:
                    if "CurrencyCode" == key2:
                        continue
                    record["ItemTax Amount"] = value[key2]
            elif "ItemPrice" == key:
                if isinstance(value, str):
                    value = {"ItemPrice Amount": ""}
                for key2 in value:
                    if "CurrencyCode" == key2:
                        continue
                    record["ItemPrice Amount"] = value[key2]
            elif "ProductInfo" == key:
                if isinstance(value, str):
                    value = {"ProductInfo NumberOfItems": ""}
                for key2 in value:
                    if "CurrencyCode" == key2:
                        continue
                    record["ProductInfo NumberOfItems"] = value[key2]
            elif "PromotionIds" == key:
                if isinstance(value, str):
                    value = {"PromotionIds PromotionId": ""}
                for key2 in value:
                    if "CurrencyCode" == key2:
                        continue
                    record["PromotionIds PromotionId"] = value[key2]
            elif "PromotionDiscount" == key:
                if isinstance(value, str):
                    value = {"PromotionDiscount Amount": ""}
                for key2 in value:
                    if "CurrencyCode" == key2:
                        continue
                    record["PromotionDiscount Amount"] = value[key2]
            elif "AmazonOrderId" == key:
                LOG.info("执行中 [{}] ...".format(row))
                record[key] = value
                # 获取订单信息
                column_od = {"PurchaseDate": True, "OrderType": True, "SellerOrderId": True, "PaymentMethod": True,
                             "OrderStatus": True, "SalesChannel": True}
                orders = mongo.query(db, "AmazonJPOrders2020", {"AmazonOrderId": value}, column_od)
                if orders is None or orders[0] is None:
                    continue
                for key3 in column_od:
                    try:
                        record[key3] = orders[0][key3]
                    except KeyError:
                        record[key3] = ""
                        continue
            else:
                record[key] = value
        row += 1
        records.append(record)
    # 写入excel文件
    # excel_utils.write_excel(excel_file, "Sheet1", records)
    excel_utils.write_excel_append(excel_file, "Sheet1", records, sheet=0)


def export_data4(excel_file, db="oms", tb=None, order_ids=None, column=None):
    params = {}
    if order_ids is not None and (isinstance(order_ids, list) and len(order_ids) > 0):
        params = {"AmazonOrderId": {"$in": order_ids}}
    mongo = Mongo()
    documents = mongo.query(db, tb, params, column)
    # 数据处理
    records = []
    for document in documents:
        record = {}
        for key in column:
            try:
                record[key] = document[key]
            except KeyError:
                record[key] = ""
                continue
        records.append(record)
    excel_utils.write_excel_append2(excel_file, records, sheet=0)
